<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Library\OSS;
use App\Modules\Comment\Models\Comment;
use App\Modules\Shop\Shop;
use App\Modules\User\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class CommentController extends Controller
{
    public function commentsIndex(Request $request)
    {
        $this->authorize('comment');
        $link_id = $request->input('link_id');
        $type = $request->input('type');
        $readNoread = $request->input('read_no_read');
        $comment = DB::table('comments AS c')
            ->leftJoin('goods AS g', 'c.link_id', '=', 'g.id')
            ->leftJoin('good_packages AS gp', 'c.link_id', '=', 'gp.id')
            ->leftJoin('shops AS s', 'g.shop_id', '=', 's.id')
            ->leftJoin('shops AS ss', 'gp.shop_id', '=', 'ss.id')
            ->when(!is_null($type), function ($query) use ($type) {
                return $query->where('c.type', $type);
            })
            ->when(!is_null($link_id), function ($query) use ($link_id) {
                return $query->where('c.link_id', $link_id);
            })
            ->when(!is_null($readNoread), function ($query) use ($readNoread) {
                return $query->where('c.read_noread', $readNoread);
            })
            ->where("c.is_delete", 0)
            ->where("c.pid", 0)
            ->orderBy('c.created_at', 'desc')
            ->paginate(20, ['c.*', 's.id as shop_id', 'gp.category', 'ss.id as p_shop_id']);

        $user = User::query()
            ->whereIn('id', $comment->pluck('user_id')->all())
            ->get()
            ->keyBy('id');

        // 获取回复数据
        $aCommentIds = $comment->pluck('id')->all();
        $aCommentChild = DB::table('comments')->whereIn('pid', $aCommentIds)->get(['id','pid','content'])->keyBy('pid');

        foreach ($comment as $value) {

            if ($value->type == Comment::TYPE_CROWD) {
                $value->type = "众筹";
            } elseif ($value->type == Comment::TYPE_PACKAGE) {
                $value->type = "套系";
            } else {
                $value->type = "商品";
            }
            if (!empty($value->image)) {
                if (gettype($value->image) == "string") {
                    $value->image = json_decode($value->image, true);
                }
                foreach ($value->image as $item) {
                    $image[] = OSS::instance()->getUrl($item);
                }
                $value->image = implode($image, ";");
            }

            foreach ($aCommentChild as $k => $v) {
                if($k == $value->id)
                    $value->child = $v;
                else
                    $value->child = '';
            }
        }

        $allShop = Shop::query()->get()->pluck('name', 'id')->all();
        $types = [/*"crowd" => "众筹",*/
            "good" => "商品",
            "package" => "套系"];
        return view('comment.index', compact('comment','readNoread','allShop', 'user', 'link_id', 'type', 'types'));
    }

    public function hideComment($id, $is_show)
    {
        $this->authorize('comment-edit');
        Comment::query()
            ->where('id', $id)
            ->orWhere('pid', $id)
            ->update([
                'is_show' => $is_show,
            ]);
        return redirect()->back();
    }

    public function destroy($id)
    {
        $this->authorize('comment-delete');
        Comment::query()
            ->where('id', $id)
            ->orWhere('pid', $id)
            ->update(['is_delete' => 1]);
        return redirect()->back();
    }


    /**
     * 系统回复
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function systemReply(Request $request)
    {
        $this->authorize('comment-edit');
        $id = $request->input('id');
        $system_reply = $request->input('system_reply');
        $user = Auth::user();
        $system_responder = $user->name;
        Comment::query()
            ->where('id', $id)
            ->update([
                'system_reply' => $system_reply,
                'system_responder' => $system_responder,
                'system_reply_username' => $user->username

            ]);
        return redirect()->back();
    }

    /**
     * 根据pid查询评论内容
     */
    public function getCommentByPid($pid)
    {
        $this->authorize('comment');
        $comment = DB::table('comments AS c')
            ->leftJoin('goods AS g', 'c.link_id', '=', 'g.id')
            ->leftJoin('good_packages AS gp', 'c.link_id', '=', 'gp.id')
            ->leftJoin('shops AS s', 'g.shop_id', '=', 's.id')
            ->leftJoin('shops AS ss', 'gp.shop_id', '=', 'ss.id')
            ->where("c.is_delete", 0)
            ->where("c.pid", $pid)
            ->orderBy('c.created_at', 'desc')
            ->get(['c.*', 's.id as shop_id', 'gp.category', 'ss.id as p_shop_id']);
        return response()->json(["data" => $comment]);
    }


    /**
     * 商家回复
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function merchantReply(Request $request)
    {
        $this->authorize('merchant_staff_and_package_comment_reply');
        $content = $request->input('content');
        $pid = $request->input('pid');
        $user = Auth::user();
        $merchant_reply = $user->name;
        $upComment = DB::table("comments")->where("id", $pid)->first();
        $data = [
            "user_id" => 0,
            "link_id" => $upComment->link_id,
            "type" => $upComment->type,
            "is_checked" => $upComment->is_checked,
            "score" => $upComment->score,
            "is_show" => $upComment->is_show,
            "pid" => $pid,
            "content" => $content,
            "merchant_reply_username" => $merchant_reply,
            'system_reply_username' => $user->username
        ];
        Comment::query()->create($data);
        return redirect()->back();
    }


    /**
     * 商家评价删除
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function merchantDel($id)
    {
        $this->authorize('merchant_staff_and_package_comment_del');
        Comment::query()
            ->where('id', $id)
            ->orWhere('pid', $id)
            ->update(['is_delete' => 1]);
        return redirect()->back();
    }


    /**
     * 评论的已读操作
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function read($id){
        $this->authorize('comment-read');
        Comment::query()
            ->where('id', $id)
            ->update([
                'read_noread' => 1,
            ]);
        return redirect()->back();
    }

}
